// api.js - 封装所有与后端的通信方法 (v1.0.1)

// 确保window.api存在
window.api = window.api || {};

// 用户API方法定义
window.api.user = {
    getList: (searchKeyword, currentPage, pageSize) => mockAPIResponse({
        data: mockUsers.filter(user => 
            !searchKeyword || 
            user.username.includes(searchKeyword) || 
            user.email.includes(searchKeyword) || 
            user.phone.includes(searchKeyword)
        ),
        total: mockUsers.length
    }),
    getDetail: (id) => mockAPIResponse(mockUsers.find(user => user.id == id)),
    update: (id, data) => {
        const index = mockUsers.findIndex(user => user.id == id);
        if (index !== -1) {
            mockUsers[index] = { ...mockUsers[index], ...data };
            return mockAPIResponse(mockUsers[index]);
        }
        return mockAPIResponse(null);
    }
};

// 基础URL
const BASE_URL = 'https://api.example.com';

// 请求头配置
const headers = {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${localStorage.getItem('token') || ''}`
};

// 更新请求头中的token
function updateAuthHeader() {
    headers['Authorization'] = `Bearer ${localStorage.getItem('token') || ''}`;
}

// 处理响应
async function handleResponse(response) {
    if (!response.ok) {
        if (response.status === 401) {
            // 未授权，跳转到登录页
            localStorage.removeItem('token');
            window.location.href = '../../人力资源管理系统/index.html';
            return Promise.reject(new Error('未授权，请重新登录'));
        }
        throw new Error(`HTTP error! status: ${response.status}`);
    }
    return response.json();
}

// GET请求
async function get(url, params = {}) {
    updateAuthHeader();
    // 构建查询字符串
    const queryString = new URLSearchParams(params).toString();
    const fullUrl = queryString ? `${BASE_URL}${url}?${queryString}` : `${BASE_URL}${url}`;

    try {
        const response = await fetch(fullUrl, {
            method: 'GET',
            headers
        });
        return handleResponse(response);
    } catch (error) {
        console.error('GET request failed:', error);
        throw error;
    }
}

// POST请求
async function post(url, data = {}) {
    updateAuthHeader();
    try {
        const response = await fetch(`${BASE_URL}${url}`, {
            method: 'POST',
            headers,
            body: JSON.stringify(data)
        });
        return handleResponse(response);
    } catch (error) {
        console.error('POST request failed:', error);
        throw error;
    }
}

// PUT请求
async function put(url, data = {}) {
    updateAuthHeader();
    try {
        const response = await fetch(`${BASE_URL}${url}`, {
            method: 'PUT',
            headers,
            body: JSON.stringify(data)
        });
        return handleResponse(response);
    } catch (error) {
        console.error('PUT request failed:', error);
        throw error;
    }
}

// DELETE请求
async function del(url) {
    updateAuthHeader();
    try {
        const response = await fetch(`${BASE_URL}${url}`, {
            method: 'DELETE',
            headers
        });
        return handleResponse(response);
    } catch (error) {
        console.error('DELETE request failed:', error);
        throw error;
    }
}

// 员工相关API
const employeeAPI = {
    // 获取员工列表
    getList: (params) => get('/employees', params),
    // 获取员工详情
    getDetail: (id) => get(`/employees/${id}`),
    // 添加员工
    add: (data) => post('/employees', data),
    // 更新员工
    update: (id, data) => put(`/employees/${id}`, data),
    // 删除员工
    delete: (id) => del(`/employees/${id}`)
};

// 业务相关API
const businessAPI = {
    // 获取业务列表
    getList: (params) => get('/businesses', params),
    // 获取业务详情
    getDetail: (id) => get(`/businesses/${id}`),
    // 创建业务
    create: (data) => post('/businesses', data),
    // 更新业务
    update: (id, data) => put(`/businesses/${id}`, data),
    // 删除业务
    delete: (id) => del(`/businesses/${id}`),
    // 获取业务报表
    getReport: (id) => get(`/businesses/${id}/report`)
};

// 薪酬相关API
const salaryAPI = {
    // 获取薪酬概览
    getOverview: (params) => get('/salaries/overview', params),
    // 获取薪酬详情
    getDetails: (params) => get('/salaries/details', params),
    // 管理薪酬
    manage: (data) => post('/salaries/manage', data)
};

// 用户相关API
const userAPI = {
    // 获取用户列表
    getList: (params) => get('/users', params),
    // 获取用户详情
    getDetail: (id) => get(`/users/${id}`),
    // 更新用户信息
    update: (id, data) => put(`/users/${id}`, data),
    // 更改密码
    changePassword: (data) => post('/users/change-password', data)
};

// 导出API
window.api = {
    employee: employeeAPI,
    business: businessAPI,
    salary: salaryAPI,
    user: userAPI,
    get, post, put, del
};

// 模拟API响应（前端演示用）
function mockAPIResponse(data, delay = 500) {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve(data);
        }, delay);
    });
}

// 模拟数据（模块级别作用域）
const mockEmployees = [
        { id: 1, name: '张三', age: 30, position: '经理', department: '技术部', hireDate: '2020-01-15', salary: 15000 },
        { id: 2, name: '李四', age: 28, position: '主管', department: '技术部', hireDate: '2021-03-22', salary: 12000 },
        { id: 3, name: '王五', age: 25, position: '专员', department: '市场部', hireDate: '2022-05-10', salary: 8000 },
        { id: 4, name: '赵六', age: 26, position: '专员', department: '人事部', hireDate: '2021-07-05', salary: 9000 },
        { id: 5, name: '钱七', age: 32, position: '总监', department: '销售部', hireDate: '2019-11-30', salary: 20000 }
    ];
// 重写API方法以使用模拟数据（仅用于演示）
// 模拟业务数据
const mockBusinesses = [
        { id: 1, name: '项目A', description: '企业官网重构', startDate: '2023-01-01', endDate: '2023-03-31', status: '已完成', revenue: 500000 },
        { id: 2, name: '项目B', description: '移动端应用开发', startDate: '2023-02-15', endDate: '2023-06-30', status: '进行中', revenue: 800000 },
        { id: 3, name: '项目C', description: '数据分析系统', startDate: '2023-04-01', endDate: '2023-08-31', status: '进行中', revenue: 600000 }
    ];

    // 模拟薪酬数据
    const mockSalaries = [
        { id: 1, employeeId: 1, employeeName: '张三', month: '2023-05', basicSalary: 15000, bonus: 5000, deduction: 1000, total: 19000 },
        { id: 2, employeeId: 2, employeeName: '李四', month: '2023-05', basicSalary: 12000, bonus: 3000, deduction: 800, total: 14200 },
        { id: 3, employeeId: 3, employeeName: '王五', month: '2023-05', basicSalary: 8000, bonus: 1000, deduction: 500, total: 8500 },
        { id: 4, employeeId: 4, employeeName: '赵六', month: '2023-05', basicSalary: 9000, bonus: 1500, deduction: 600, total: 9900 },
        { id: 5, employeeId: 5, employeeName: '钱七', month: '2023-05', basicSalary: 20000, bonus: 8000, deduction: 1200, total: 26800 }
];

// 模拟用户数据
const mockUsers = [
    { id: 1, username: 'admin', name: '管理员', role: 'admin', email: 'admin@example.com', phone: '13800138000' },
    { id: 2, username: 'manager', name: '部门经理', role: 'manager', email: 'manager@example.com', phone: '13900139000' },
    { id: 3, username: 'user', name: '普通用户', role: 'user', email: 'user@example.com', phone: '13700137000' }
];

    // 重写API方法
    window.api.employee.getList = () => mockAPIResponse({ data: mockEmployees });
    window.api.employee.getDetail = (id) => mockAPIResponse(mockEmployees.find(item => item.id === id));
    window.api.employee.add = (data) => {
        const newItem = { ...data, id: mockEmployees.length + 1 };
        mockEmployees.push(newItem);
        return mockAPIResponse(newItem);
    };
    window.api.employee.update = (id, data) => {
        const index = mockEmployees.findIndex(item => item.id === id);
        if (index !== -1) {
            mockEmployees[index] = { ...mockEmployees[index], ...data };
            return mockAPIResponse(mockEmployees[index]);
        }
        return mockAPIResponse(null);
    };
    window.api.employee.delete = (id) => {
        const index = mockEmployees.findIndex(item => item.id === id);
        if (index !== -1) {
            mockEmployees.splice(index, 1);
            return mockAPIResponse({ success: true });
        }
        return mockAPIResponse({ success: false });
    };

    // 业务API模拟
    window.api.business.getList = () => mockAPIResponse({ data: mockBusinesses });
    window.api.business.getDetail = (id) => mockAPIResponse(mockBusinesses.find(item => item.id === id));
    window.api.business.create = (data) => {
        const newItem = { ...data, id: mockBusinesses.length + 1 };
        mockBusinesses.push(newItem);
        return mockAPIResponse(newItem);
    };
    window.api.business.update = (id, data) => {
        const index = mockBusinesses.findIndex(item => item.id === id);
        if (index !== -1) {
            mockBusinesses[index] = { ...mockBusinesses[index], ...data };
            return mockAPIResponse(mockBusinesses[index]);
        }
        return mockAPIResponse(null);
    };
    window.api.business.delete = (id) => {
        const index = mockBusinesses.findIndex(item => item.id === id);
        if (index !== -1) {
            mockBusinesses.splice(index, 1);
            return mockAPIResponse({ success: true });
        }
        return mockAPIResponse({ success: false });
    };
    window.api.business.getReport = (id) => {
        const business = mockBusinesses.find(item => item.id === id);
        if (business) {
            return mockAPIResponse({
                businessId: business.id,
                businessName: business.name,
                totalRevenue: business.revenue,
                expenses: business.revenue * 0.6,
                profit: business.revenue * 0.4,
                status: business.status
            });
        }
        return mockAPIResponse(null);
    };

    // 薪酬API模拟
    window.api.salary.getOverview = () => mockAPIResponse({
        totalEmployees: mockSalaries.length,
        totalSalary: mockSalaries.reduce((sum, item) => sum + item.total, 0),
        averageSalary: mockSalaries.reduce((sum, item) => sum + item.total, 0) / mockSalaries.length,
        departmentDistribution: [
            { department: '技术部', count: 2, totalSalary: 33200 },
            { department: '市场部', count: 1, totalSalary: 8500 },
            { department: '人事部', count: 1, totalSalary: 9900 },
            { department: '销售部', count: 1, totalSalary: 26800 }
        ]
    });
    window.api.salary.getDetails = () => mockAPIResponse({ data: mockSalaries });

    // 用户API模拟
    window.api.user.getList = () => mockAPIResponse({ data: mockUsers });
    window.api.user.getDetail = (id) => mockAPIResponse(mockUsers.find(item => item.id === id));
    window.api.user.update = (id, data) => {
        const index = mockUsers.findIndex(item => item.id === id);
        if (index !== -1) {
            mockUsers[index] = { ...mockUsers[index], ...data };
            return mockAPIResponse(mockUsers[index]);
        }
        return mockAPIResponse(null);
    };


// 初始化API
updateAuthHeader();

// 兼容旧版非模块环境
if (typeof window !== 'undefined') {
    window.api = window.api || {};
}
// 移除ES6导出，仅通过window对象暴露API
// export { api };

// 初始化API
updateAuthHeader();